<?php

namespace App\Jobs;

use App\Models\User;
use App\Models\Order;
use App\Models\OrderItem;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldBeUnique;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use Illuminate\Support\Facades\Redis;
use Illuminate\Support\Facades\DB;
use Carbon\Carbon;
use App\Events\OrderPaidEvent;


class PayCacheOrderJob implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;


    protected User $user;

    protected $cacheId = null;
    /**
     * Create a new job instance.
     *
     * @return void
     */
    public function __construct(User $user, $cacheId)
    {
        $this->user = $user;
        $this->cacheId = $cacheId;
    }

    /**
     * Execute the job.
     *
     * @return void
     */
    public function handle()
    {
        $orderId = Redis::hGet($this->cacheId,'order_id');
        if($orderId){

            $order = Order::find($orderId);

            DB::transaction(function () use ($order,$orderId) {


                 $order->update(['paid_at' => Carbon::now(), 'paid_method' => 'balance']);
                 $balances = $order->total_amount;
                 $data = ['order_id' => $orderId];
                 account_balances($this->user)->minusOrderPaid($balances, $data);
                 $lowestAmountPercent = cs('good')->lowest_amount_percent*100;
                 $highestAmountPercent = cs('good')->highest_amount_percent*100;
                 $random = rand($lowestAmountPercent,$highestAmountPercent)/10000;
                 $brokerages = big_decimal($balances)->multipliedBy($random);

                 $orderItem = OrderItem::query()->where('order_id',$orderId)->first();
                 $data['product_id'] = $orderItem->product_id;
                 $data['product_sku_id'] = $orderItem->product_sku_id;
                 $data['seckill_product_id'] = $order->seckill_id;
                 $data['pay_money'] = $order->total_amount;
                 account_brokerages($this->user)->userOrderPaid($brokerages, $data);

                 $isNew = Redis::hGet($this->user->infoCacheKey(),"is_new");

                 if($isNew == 1){
                    $this->user->update(['is_new' => 0]);
                    Redis::hMset($this->user->infoCacheKey(),["is_new" => false]);
                 }
                 if($this->user->parent_id){
                    $parentUser = User::find($this->user->parent_id);
                    account_brokerages($parentUser)->orderPaid($balances*0.01, $data);

                }
                event(new OrderPaidEvent($order));
                $order->unsetRelations();
                return $order;
             });
        }
    }
}
